package com.zzuli.xyd.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zzuli.xyd.pojo.BatchIds;
import com.zzuli.xyd.pojo.LoginUser;
import com.zzuli.xyd.pojo.Result;
import com.zzuli.xyd.pojo.Userinfo;
import com.zzuli.xyd.service.IUserService;
import com.zzuli.xyd.util.JWTUtils;
import com.zzuli.xyd.util.MDigest5;
import com.zzuli.xyd.util.PageUtil;
import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @auther pony
 * @create 2022-07-05 15:17
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 登陆
     * @param userinfo
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody Userinfo userinfo){

        //1、获取用户名
        String username = userinfo.getUsername();
        String userpwd = userinfo.getUserpwd();

        //创建
        Result result = new Result();

        //2、验证数据有效性
        if (username==null ||"".equals(username.trim())){
            result.setStatusCode(303);
            result.setMessage("用户名不能为空");
            return result;
        }

        if (userpwd==null ||"".equals(userpwd.trim())){
            result.setStatusCode(303);
            result.setMessage("密码不能为空");
            return result;
        }

        //3、判断用户名是否存在
        try {
            Userinfo resultUser = userService.ckUsername(userinfo.getUsername());
            if (resultUser!=null){ //存在此用户
                //4、判断密码，加密后，在与数据库对比
                if(MDigest5.getMD5(userpwd).equals(resultUser.getUserpwd())){
                    //5、登陆成功，生成token（密钥），返回数据
                    String jwtToken = JWTUtils.createJwtToken(resultUser.getId().toString(), resultUser.getUsername());
                    //封装实体，登陆乘客
                    LoginUser loginUser = new LoginUser();
                    loginUser.setUserid(resultUser.getId());
                    loginUser.setUsername(resultUser.getUsername());
                    loginUser.setJwtToken(jwtToken);
                    //登陆成功，设置返回数据
                    result.setStatusCode(200);
                    result.setMessage("登陆成功");
                    result.setData(loginUser);
                }else {
                    result.setStatusCode(300);
                    result.setMessage("登陆失败，密码不正确");
                }
            }else {//不存在此用户
                result.setStatusCode(404);
                result.setMessage("登陆失败，不存在此用户名");
            }
        }catch (Exception e){
            result.setStatusCode(500);
            result.setMessage("登陆失败，请与管理员联系");
        }
        return result;
    }

    /**
     * 注册
     * @param userinfo
     * @return
     */
    @RequestMapping("/register")
    public Result register(@RequestBody Userinfo userinfo){
        //1、获取用户名和密码
        String username = userinfo.getUsername();
        String ouserpwd = userinfo.getUserpwd();

        Result result = new Result();

        //2、验证数据有效性
        if (username==null ||"".equals(username.trim())){
            result.setStatusCode(303);
            result.setMessage("用户名不能为空");
            return result;
        }

        if (ouserpwd==null ||"".equals(ouserpwd.trim())){
            result.setStatusCode(303);
            result.setMessage("密码不能为空");
            return result;
        }

        //3、判断用户名是否存在
        try {
            Userinfo resultUser = userService.ckUsername(username);
            if (resultUser!=null){ //存在此用户
                result.setStatusCode(300);
                result.setMessage("注册失败，此用户名已被使用");
            }else {//不存在此用户
                //4、将密码加密
                String userpwd = MDigest5.getMD5(ouserpwd);
                //封装数据
                Userinfo userinfo1 = new Userinfo(username, userpwd);
                //添加用户
                Boolean aBoolean = userService.addUser(userinfo1);
                if (aBoolean){
                    result.setStatusCode(200);
                    result.setMessage("注册成功");
                }else {
                    result.setStatusCode(400);
                    result.setMessage("注册失败，请与管理员联系");
                }
            }
        }catch (Exception e){
            result.setStatusCode(500);
            result.setMessage("注册失败，请与管理员联系");
        }
        return result;
    }

    /**
     * 重置密码
     * @param userinfo
     * @return
     */
    @RequestMapping("/repwd")
    public Result repwd(@RequestBody Userinfo userinfo){
        //1、获取用户名和密码
        String username = userinfo.getUsername();
        String iuserpwd = userinfo.getUserpwd();

        Result result = new Result();

        //2、验证数据有效性
        if (username==null ||"".equals(username.trim())){
            result.setStatusCode(303);
            result.setMessage("用户名不能为空");
            return result;
        }

        if (iuserpwd==null ||"".equals(iuserpwd.trim())){
            result.setStatusCode(303);
            result.setMessage("密码不能为空");
            return result;
        }

        //3、判断用户名是否存在
        try {
            Userinfo resultUser = userService.ckUsername(username);
            if (resultUser!=null){ //存在此用户
                //4、将密码加密
                String userpwd = MDigest5.getMD5(iuserpwd);
                //封装数据
                Userinfo userinfo1 = new Userinfo(username, userpwd);
                //修改密码
                Boolean aBoolean = userService.rePwd(userinfo1);

                if (aBoolean){
                    result.setStatusCode(200);
                    result.setMessage("修改成功");
                }else {
                    result.setStatusCode(400);
                    result.setMessage("修改失败，请与管理员联系");
                }
            }else {//不存在此用户
                result.setStatusCode(500);
                result.setMessage("修改失败，用户不存在");
            }
        }catch (Exception e){
            result.setStatusCode(500);
            result.setMessage("修改失败，请与管理员联系");
        }
        return result;
    }

    /**
     * 查找是否存在此用户名
     * @param userinfo
     * @return
     */
    @RequestMapping("/ckuser")
    public Result ckUserName(@RequestBody Userinfo userinfo){
        Result result = new Result();
        try{
            Userinfo reuserinfo = userService.ckUsername(userinfo.getUsername());
            if(reuserinfo!=null){  // 存在此用户名
                result.setStatusCode(200);
                result.setMessage("✘此用户名已被注册");
            }
            else{ // 不存在此用户
                result.setStatusCode(404);
                result.setMessage("✔此用户名可以使用");
            }
        }catch (Exception ex){
            result.setStatusCode(500);
            result.setMessage("查找用户名出错了，请与管理者");
        }
        return result;
    }

    /**
     * 用户添加
     * @param userinfo
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Userinfo userinfo){
        //1、获取用户名和密码
        String username = userinfo.getUsername();
        String ouserpwd = userinfo.getUserpwd();

        Result result = new Result();

        //2、验证数据有效性
        if (username==null ||"".equals(username.trim())){
            result.setStatusCode(303);
            result.setMessage("用户名不能为空");
            return result;
        }

        if (ouserpwd==null ||"".equals(ouserpwd.trim())){
            result.setStatusCode(303);
            result.setMessage("密码不能为空");
            return result;
        }

        //3、判断用户名是否存在
        try {
            Userinfo resultUser = userService.ckUsername(username);
            if (resultUser!=null){ //存在此用户
                result.setStatusCode(300);
                result.setMessage("添加失败，此用户名已被使用");
            }else {//不存在此用户
                //4、将密码加密
                userinfo.setUserpwd(MDigest5.getMD5(userinfo.getUserpwd()));
                //添加用户
                Boolean aBoolean = userService.addUser(userinfo);
                if (aBoolean){
                    result.setStatusCode(200);
                    result.setMessage("添加成功");
                }else {
                    result.setStatusCode(400);
                    result.setMessage("添加失败，请与管理员联系");
                }
            }
        }catch (Exception e){
            result.setStatusCode(500);
            result.setMessage("添加失败，请与管理员联系");
        }
        return result;
    }

    /**
     * 按id查询数据
     * @param id
     * @return
     */
    @RequestMapping("/findbyid/{id}")
    public Result findById(@PathVariable("id") Integer id){
        Result result = new Result();
        try{
            Userinfo model = userService.findById(id);
            if(model!=null){  // 存在此用户名
                result.setStatusCode(200);
                result.setMessage("success");
                result.setData(model);
            }
            else{ // 不存在此用户
                result.setStatusCode(300);
                result.setMessage("没有查找数据");
            }
        }catch (Exception ex){
            System.out.println(ex);
            result.setStatusCode(500);
            result.setMessage("查找数据出错，请与管理员联系");
        }
        return result;
    }

    /**
     * 修改
     * @param model
     * @return
     */
    @RequestMapping("/update")
    public Result update(@RequestBody Userinfo model){
        Result result = new Result();
        try{
            int rows = userService.update(model);
            if(rows>0){  // 存在此用户名
                result.setStatusCode(200);
                result.setMessage("已成功修改了工作人员的数据");
            }
            else{ // 不存在此用户
                result.setStatusCode(300);
                result.setMessage("修改工作人员失败");
            }
        }catch (Exception ex){
            System.out.println(ex);
            result.setStatusCode(500);
            result.setMessage("修改数据出错，请与管理员联系");
        }
        return result;
    }

    /**
     * 删除用户
     * @param ids
     * @return
     */
    @RequestMapping("/del")
    public Result deleteBatchIds(@RequestBody BatchIds ids){
        Result result = new Result();
        try{
            int rows = userService.deleteBatch(ids.getIds());
            if(rows>0){  // 存在此用户名
                result.setStatusCode(200);
                result.setMessage("已成功删除工作人员的数据");
            }
            else{ // 不存在此用户
                result.setStatusCode(300);
                result.setMessage("删除工作人员失败");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(ex);
            result.setStatusCode(500);
            result.setMessage("删除数据出错，请与管理员联系");

        }


        return result;
    }

    /**
     * 加载数据
     * @param pageIndex
     * @param pageSize
     * @param keyword
     * @return
     */
    @RequestMapping({"/getpagelist/{pageIndex}/{pageSize}/{keyword}","/getpagelist/{pageIndex}/{pageSize}"})
    public Result getPageList(@PathVariable("pageIndex") Integer pageIndex, @PathVariable("pageSize") Integer pageSize, @PathVariable(value = "keyword",required = false) String keyword){
        Result result = new Result();
        try{
            // 分页查询数据
            PageUtil<Userinfo> membersPage = userService.getUserinfoPage(pageIndex, pageSize,keyword);
            if(membersPage!=null){
                result.setStatusCode(200);
                result.setMessage("success");
                result.setData(membersPage);
            }
            else{
                result.setStatusCode(404);
                result.setMessage("没有查询到数据");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(ex.toString());
            result.setStatusCode(500);
            result.setMessage("查询数据出错，请与管理员了联系");
        }
        return result;
    }
}
